package com.interview.two.service;

import com.interview.two.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;

@Slf4j
public class TestService7 {

    public static void main(String[] args) throws InterruptedException {
        GenericApplicationContext context = new GenericApplicationContext();
        AnnotationConfigUtils.registerAnnotationConfigProcessors(context.getDefaultListableBeanFactory());
        ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
        context.registerBean(AppConfig.class);
        context.refresh();

        Service7 bean = context.getBean(Service7.class);

        Object lock = new Object();
        new MyThread(() -> {
            synchronized (lock) {
                bean.transfer(1, 2, 1000);
            }

        }, "t1", "boldMagenta").start();

        new MyThread(() -> {
            synchronized (lock){
                bean.transfer(1, 2, 1000);
            }
        }, "t2", "boldBlue").start();

        Thread.sleep(100);
        log.error("最后的余额，期望余额为0，实际余额为：{}", bean.findBalance(1));
    }

    static class MyThread extends Thread {
        private String color;

        public MyThread(Runnable target, String name, String color) {
            super(target, name);
            this.color = color;
        }

        @Override
        public void run() {
            MDC.put("thread", color);
            super.run();
            MDC.remove("thread");
        }
    }
}
